package com.horsen.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.horsen.common.util.R;
import com.horsen.service.edu.mapper.CourseMapper;
import com.horsen.service.edu.mapper.TeacherMapper;
import com.horsen.service.edu.model.BO.TeacherOutputBO;
import com.horsen.service.edu.model.Course;
import com.horsen.service.edu.model.DTO.TeacherInsertDTO;
import com.horsen.service.edu.model.DTO.TeacherQueryDTO;
import com.horsen.service.edu.model.DTO.TeacherUpdateDTO;
import com.horsen.service.edu.model.Teacher;
import com.horsen.service.edu.service.TeacherService;
import com.horsen.service.edu.service.feign.OSSFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 讲师 服务实现类
 *
 * @author Horsen
 */
@Service
@Slf4j
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    private OSSFileService ossFileService;
    @Autowired
    private CourseMapper courseMapper;

    /**
     * 分页查询
     *
     * @param page            当前页码
     * @param limit           每页记录数
     * @param teacherQueryDTO 讲师查询DTO
     * @return IPage类实例
     */
    @Override
    public IPage<Teacher> pageSelect(Long page, Long limit, TeacherQueryDTO teacherQueryDTO) {
        // 创建条件构造器
        LambdaQueryWrapper<Teacher> queryWrapper = Wrappers.lambdaQuery();
        // 设置orderBy关键字
        queryWrapper.orderByDesc(Teacher::getSort);
        if (teacherQueryDTO != null) {
            String name = teacherQueryDTO.getName();
            Integer level = teacherQueryDTO.getLevel();
            String joinDateBegin = teacherQueryDTO.getJoinDateBegin();
            String joinDateEnd = teacherQueryDTO.getJoinDateEnd();
            // 设置查询条件
            if (!StringUtils.isEmpty(name)) {
                queryWrapper.like(Teacher::getName, name);
            }
            if (level != null) {
                queryWrapper.eq(Teacher::getLevel, level);
            }
            if (!StringUtils.isEmpty(joinDateBegin)) {
                queryWrapper.ge(Teacher::getJoinDate, joinDateBegin);
            }
            if (!StringUtils.isEmpty(joinDateEnd)) {
                queryWrapper.le(Teacher::getJoinDate, joinDateEnd);
            }
        }
        return baseMapper.selectPage(new Page<>(page, limit), queryWrapper);
    }

    /**
     * 新增一个讲师
     *
     * @param teacherInsertDTO 讲师插入DTO
     * @return 插入是否成功
     */
    @Override
    public Boolean insert(TeacherInsertDTO teacherInsertDTO) {
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherInsertDTO, teacher);
        return this.save(teacher);
    }

    /**
     * 修改一个讲师
     *
     * @param teacherUpdateDTO 讲师更新DTO
     * @return 修改是否成功
     */
    @Override
    public Boolean updateById(TeacherUpdateDTO teacherUpdateDTO) {
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherUpdateDTO, teacher);
        return this.updateById(teacher);
    }

    /**
     * 根据姓氏获取讲师姓名列表
     *
     * @param key 姓氏
     * @return 讲师姓名列表
     */
    @Override
    public List<Map<String, Object>> queryNamesByKey(String key) {
        // 创建条件构造器
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Teacher::getName).likeRight(Teacher::getName, key);
        return baseMapper.selectMaps(queryWrapper);
    }

    /**
     * 根据讲师ID删除头像
     *
     * @param id 讲师ID
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteAvatarById(String id) {
        Teacher teacher = baseMapper.selectById(id);
        // 确保讲师存在
        if (teacher != null) {
            String url = teacher.getAvatar();
            // 确保讲师有头像
            if (!StringUtils.isEmpty(url)) {
                R result = ossFileService.delete(url);
                // 返回成功结果
                return result.getSuccess();
            }
        }
        return false;
    }

    /**
     * 根据ID删除讲师
     *
     * @param id 讲师ID
     * @return 删除是否成功
     */
    @Override
    public Boolean deleteById(String id) {
        LambdaUpdateWrapper<Teacher> updateWrapper = Wrappers.lambdaUpdate();
        // 设置avatar字段为null
        updateWrapper.set(Teacher::getAvatar, null);
        updateWrapper.eq(Teacher::getId, id);
        // 删除讲师头像
        if (this.deleteAvatarById(id)) {
            log.info("删除讲师头像成功");
        } else {
            log.info("删除讲师头像失败");
        }
        // 删除url字段
        this.update(updateWrapper);
        // 逻辑删除讲师
        return this.removeById(id);
    }

    /**
     * 导出讲师到Excel文件
     *
     * @param list 讲师列表
     * @return 文件位置
     */
    @Override
    public String output(List<TeacherOutputBO> list) {
        String dateTime = new DateTime().toString("yy-MM-dd-HH-mm-ss");
        System.out.println(dateTime);
        String filePath = "E:/Proj_Java/hsedu/excel/teacher_" + dateTime + ".xlsx";
        EasyExcel.write(filePath, TeacherOutputBO.class)
                .sheet("讲师信息")
                .doWrite(list);
        return filePath;
    }

    /**
     * 根据讲师ID获取详情
     *
     * @param id 讲师ID
     * @return 详情Map
     */
    @Override
    public Map<String, Object> queryInfoById(String id) {
        // 获取讲师
        Teacher teacher = baseMapper.selectById(id);
        // 获取该讲师的课程
        LambdaQueryWrapper<Course> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Course::getTeacherId, id).
                eq(Course::getStatus, Course.COURSE_STATE_PASS);
        List<Course> courseList = courseMapper.selectList(queryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("teacher", teacher);
        map.put("courseList", courseList);
        return map;
    }
}
